package com.uwantsoft.business.infrastructure.repository.querier;


import com.uwantsoft.business.facade.dto.parking.ParkOverviewQueryCondition;
import com.uwantsoft.business.service.domain.park.Park;
import com.uwantsoft.util.paging.AbstractQuerier;
import com.uwantsoft.util.paging.ParameterFilter;
import org.hibernate.Query;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.util.StringUtils;

/**
 * @author LeiPeichen.
 */
public class ParkOverviewQuerier extends AbstractQuerier<Park> {

    private ParkOverviewQueryCondition parkOverviewQueryCondition;

    public ParkOverviewQuerier(HibernateTemplate hibernateTemplate,ParkOverviewQueryCondition parkOverviewQueryCondition) {
        super(hibernateTemplate);
        this.parkOverviewQueryCondition = parkOverviewQueryCondition;
        addNameFilter();
    }

    private void addNameFilter() {
        final String name = parkOverviewQueryCondition.getName();
        if (StringUtils.hasText(name)) {
            addFilter(new ParameterFilter() {
                @Override
                public void setParameter(Query query) {
                    query.setParameter("name", "%" + name + "%");
                }
                @Override
                public String getSubHql() {
                    return "and p.name like :name";
                }
            });
        }
    }

    @Override
    public int getStartPosition() {
        return parkOverviewQueryCondition.getStartIndex();
    }

    @Override
    public int getItemsAmountPerPage() {
        return parkOverviewQueryCondition.getObjectsPerPage();
    }

    @Override
    public String getResultHql() {
        return "from Park p where 1=1 " + getSubHql();
    }

    @Override
    public String getAmountHql() {
        return "select count(*) from Park p where 1=1 " + getSubHql();
    }

}
